package cn.itsource.system.service.impl;

import cn.itsource.org.domain.Department;
import cn.itsource.system.domain.Menu;
import cn.itsource.system.mapper.MenuMapper;
import cn.itsource.system.service.IMenuService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hhm
 * @since 2023-04-01
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> tree() {

        List<Menu> firstMenuList = new ArrayList<>();

        List<Menu> all = menuMapper.queryAll();

        Map<Long, Menu> map = new HashMap<>();
        for (Menu menu : all) {
            map.put(menu.getId(), menu);
        }
        for (Menu currentMenu : all) {
            //判断通过  就是一级部门
            if (currentMenu.getParentId() == null) {
                firstMenuList.add(currentMenu);
            } else {
                //得到自己的父部门id
                Long pid = currentMenu.getParentId();
                //用父部门id去找到父部门对象
                Menu menu = map.get(pid);
                //将自己加入父级部门的children集合中
                menu.getChildren().add(currentMenu);
            }
        }
        return firstMenuList;
    }
}
